const path = require("path");
const { sep } = path;
const glob = require("glob");
/**
 * router-schema loader
 * @param {object} app koa 实例
 * 通过json-schema & ajv 对api规则进行约束，配合api-params-verify 中间件使用
 * app/router-schema/**.js 与路由同名
 *  输出app.routerSchema = {
 *    '${api}':${jsonSchema}
 *   }
 * */
module.exports = (app) => {
  const routerSchemaPath = path.resolve(
    app.businessPath,
    `.${sep}router-schema`
  );
  const fileList = glob.sync(
    path.resolve(routerSchemaPath, `.${sep}**${sep}**.js`)
  );

  // 注册所有 routerSchema,便可以 app.routerSchema这样访问
  let routerSchema = {};
  fileList.forEach((file) => {
    routerSchema = {
      ...routerSchema,
      ...require(path.resolve(file)),
    };
  });
  app.routerSchema = routerSchema;
};
